package com.dsx.dsms.controller;


import com.alibaba.fastjson.JSONObject;
import com.dsx.dsms.pojo.*;
import com.dsx.dsms.service.*;
import com.dsx.dsms.util.Common;
import com.dsx.dsms.util.Page;
import com.dsx.dsms.util.Transform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author dsx
 */
@Controller
@RequestMapping("")
public class CoachController {

    @Autowired
    CoachService coachService;
    @Autowired
    ReservationService  reservationService;
    @Autowired
    UserService userService;
    @Autowired
    StudentService studentService;
    @Autowired
    ExamInfoService examInfoService;

    @RequestMapping("admin_coach_add")
    public String coachAdd(String username, String password, String name,
                           String phone, MultipartFile pic, String sex,
                           String type, String intro, int tAge,
                           HttpServletRequest request){
        username = HtmlUtils.htmlEscape(username);
        int userNameNum= userService.getUserByUserName(username);
        if(userNameNum > 0){
            return "redirect:admin/listCoach.html?msg=-1";
        }
        Coach coach = new Coach();
        coach.setName(name);
        coach.setType(type);
        coach.setTelephone(phone);
        coach.setTage(tAge);
        coach.setIntroduce(intro);

        coachService.add(coach);
        int id = coach.getId();
        String[] arr = pic.getOriginalFilename().split("\\.");
        String picName = Transform.getRandomFileName() + "." + arr[1];
        int userType = 1;
        userService.insertUser(username,password,id, sex, picName,userType);
        String path = request.getServletContext().getRealPath("/img/coach/");
        System.out.println("path---------> " + path);
        try{
            File file = new File(path + File.separator + picName);
            pic.transferTo(file);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:admin/listCoach.html";
    }

    @ResponseBody
    @RequestMapping("admin_coach_list")
    public String list(Page page){
        List<Coach> cs =coachService.list(page);
        int total = coachService.total();
        page.setTotal(total);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cs", cs);
        jsonObject.put("page", page);
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }


    @ResponseBody
    @RequestMapping("fore_coach_list")
    public String foreList(){
        List<Coach> cs =coachService.listAll();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cs", cs);
        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("admin_coach_delete")
    public void delete(int id, HttpServletRequest request){
        User user = userService.getUserByFid(id, 1);
        String path = request.getServletContext().getRealPath("/img/coach/");
        File file = new File(path + user.getPic());
        if(file.exists()){
            file.delete();
        }
        coachService.delete(id);
        userService.delete(user.getId());
    }


    @ResponseBody
    @RequestMapping("admin_coach_time")
    public String adminTime(String t, HttpSession session){

        String str;
        Date date;
        User user = (User)session.getAttribute("coach");
        date = (t==null) ? new Date() : new Date(Long.parseLong(t));
        str = (date.getYear()+1900) + "-" + (date.getMonth() +1)+ "-" + date.getDate();
        List<Scheduling> scs = coachService.listScheduling(user.getCoach().getId(),str);

        for(int j=0; j<scs.size(); j++)
        {
            Scheduling sc = scs.get(j);
            sc.setTime();               //设置time 一天中8个时间段的的预约人数
            sc.setWeek(Transform.change(sc.getDate()));

        }
        // 设置中间部分的日期
        String currentStr = (date.getMonth() +1)+ "-" + date.getDate();
        date.setDate(date.getDate()+6);
        currentStr =currentStr + " 至 " + (date.getMonth()+1) + "-" + date.getDate();


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scs", scs);
        jsonObject.put("currentStr", currentStr);
        //当前页面的第一天
        jsonObject.put("currentDate", str);
        jsonObject.put("user",user);
        System.out.println(jsonObject.toJSONString());

        return jsonObject.toJSONString();
    }


    @ResponseBody
    @RequestMapping("admin_coach_test")
    public String test(String t, HttpSession session){
        String str;
        Date date;
        User user = (User)session.getAttribute("student");
        JSONObject jsonObject = new JSONObject();
        if( !Common.SUBJECT2.equals(user.getStudent().getSchedule()) && !Common.SUBJECT3.equals(user.getStudent().getSchedule()) ){
            // 只有科目二和科目三可以预约
            jsonObject.put("flag", -1);
            return jsonObject.toJSONString();
        }


        date = (t==null) ? new Date() : new Date(Long.parseLong(t));
        Date date1 = new Date();
        if(date1.getTime() - date.getTime() > Common.ONE_MOUTH || date1.getTime() - date.getTime() < -Common.ONE_MOUTH) {
            // 只能查看进一个月左右的预约情况
            jsonObject.put("flag", -11);
            return jsonObject.toJSONString();
        }
        str = (date.getYear()+1900) + "-" + (date.getMonth() +1)+ "-" + date.getDate();
        int id = user.getStudent().getSubject3() == 0 ? user.getStudent().getSubject2() : user.getStudent().getSubject3();
        Date tempDate = new Date();
        tempDate.setYear(date.getYear());
        tempDate.setMonth(date.getMonth());
        tempDate.setDate(date.getDate());
        List<Scheduling> scs = coachService.listScheduling(id,str);
        for(int j=0; j<scs.size(); j++)
        {
            Scheduling sc = scs.get(j);
            sc.setWeek(Transform.change(sc.getDate()));
            tempDate.setDate(date.getDate() + j);
            String tempStr = (tempDate.getYear()+1900) + "-" + (tempDate.getMonth() +1)+ "-" + tempDate.getDate();
            for(int i = 0; i<8; i++){
                //查看 str 日期  i 时间段是否预约
                int tmp = reservationService.isReservation(user.getStudent().getId(),tempStr,i);
                if(tmp > 0 ){
                    sc.setReservation(i);
                }
            }
            sc.setTime();               //设置time 一天中8个时间段的的预约人数
        }
        String currentStr = (date.getMonth() +1)+ "-" + date.getDate();
        date.setDate(date.getDate()+6);

        currentStr =currentStr + " 至 " + (date.getMonth()+1) + "-" + date.getDate();

        jsonObject.put("scs", scs);
        jsonObject.put("currentStr", currentStr);
        jsonObject.put("currentDate", str);
        jsonObject.put("user",user);
        jsonObject.put("flag",0);
        System.out.println(jsonObject.toJSONString());

        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("admin_coach_setTime")
    public String setTime(int j, Long t, int type, int flag, HttpSession session){  // t天的第j列 请求类型type 请求标志flag
        User user = (User)session.getAttribute("coach");
        Date date = new Date(t);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = sd.format(date);
        int id = user.getCoach().getId();
        Scheduling sc = coachService.getSchedulingById(id,strDate);
        sc.setTime();
        //今天
        Date date1 = new Date();
        date.setHours(8);
        JSONObject jsonObject = new JSONObject();
        //如果要请假的那天 与今天 相隔 小于 8 小时 就无法请假
        if(date.getTime() - date1.getTime() < Common.EIGHT_HOUR){
            jsonObject.put("success" , -200);
            return jsonObject.toJSONString();
        }
        int[] time = sc.getTime();
        switch (type){
            case 1:
                // 请假
                if(flag == 1){
                    time[j] = -1;
                    //设置scheduling表time1~8 的人数
                    reservationService.resetTime(id,strDate,time);
                    // 插入请假记录
                    coachService.insertLeave(id,strDate,j);
                    //删除预约记录
                    List<Student> ss = studentService.listStudentByReservationPeriod(id,strDate,j);
                    for(Student s : ss){
                        reservationService.deleteReservation(s.getId(),strDate,j);
                    }

                }
                if(flag == -1){
                    // 从reservation表中获取人数
                    time[j] = coachService.getCountByPeriod(id,strDate,j);
                    reservationService.resetTime(id,strDate,time);
                    coachService.deleteLeave(id,strDate,j);
                    System.out.println("flag44-----------> " + flag);
                }
                break;
            case 4:
                for(int i=0; i<4; i++){
                    time[i] = -1;
                    //设置scheduling表time1~8 的人数
                    reservationService.resetTime(id,strDate,time);
                    //删除预约记录
                    List<Student> ss = studentService.listStudentByReservationPeriod(id,strDate,i);
                    for(Student s : ss){
                        reservationService.deleteReservation(s.getId(),strDate,i);
                    }
                    // 插入请假记录
                    coachService.insertLeave(id,strDate,i);
                }
                break;
            case -4:
                for(int i=4; i<8; i++){
                    time[i] = -1;
                    //设置scheduling表time1~8 的人数
                    reservationService.resetTime(id,strDate,time);
                    // 插入请假记录
                    coachService.insertLeave(id,strDate,i);
                }
                break;
            case 8:
                for(int i=0; i<8; i++){
                    time[i] = -1;
                    //删除预约记录
                    List<Student> ss = studentService.listStudentByReservationPeriod(id,strDate,i);
                    for(Student s : ss){
                        reservationService.deleteReservation(s.getId(),strDate,i);
                    }
                    //设置scheduling表time1~8 的人数
                    reservationService.resetTime(id,strDate,time);
                    // 插入请假记录
                    coachService.insertLeave(id,strDate,i);
                }
                break;
            default: break;
        }
        jsonObject.put("time", time);
        jsonObject.put("success", 200);
        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("admin_coach_listByPeriod")
    public String listByPeriod(int j, Long t, HttpSession session){  // t天的第j列 预约练车的学生
        User user = (User)session.getAttribute("coach");
        int id = user.getCoach().getId();
        Date date = new Date(t);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = sd.format(date);
        List<Student> ss = studentService.listStudentByReservationPeriod(id,strDate,j);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ss",ss);
        return jsonObject.toJSONString();
    }
    @ResponseBody
    @RequestMapping("admin_coach_getMyStudent")
    public String getMyStudent(Page page, HttpSession session){

        User user = (User)session.getAttribute("coach");
        page.setCount(10);
        String type = user.getCoach().getType();
        int cid = user.getCoach().getId();
        int total = studentService.totalStudentByCid(cid, type);
        page.setTotal(total);
        List<Student> ss = studentService.listStudentByCid(cid,type,page);
        List<Integer> time  = new ArrayList<>();
        List<ExamInfo> es = new ArrayList<>();
        Date date = new Date();
        for(Student s : ss){
            time.add(coachService.totalTime(s.getId(),cid));
            ExamInfo e  = examInfoService.getExamInfoByNextTime(s.getId(),date);
            if(e != null){
                e.setDate_();
                e.setType_();
            }
            es.add(e);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ss", ss);
        jsonObject.put("page", page);
        jsonObject.put("time",time);
        jsonObject.put("es", es);
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("admin_coach_getMyStudentByExam")
    public String getMyStudentByExam(Page page, HttpSession session){

        User user = (User)session.getAttribute("coach");
        int cid = user.getCoach().getId();
        String type = user.getCoach().getType();
        int subject2=0,subject3=0;
        if(Common.SUBJECT2.equals(type)){
            subject2 = cid;
        }
        else{
            subject3 = cid;
        }
        Date date = new Date();
        page.setCount(10);
        int total = studentService.totalStudentByNextTimeExam(subject2, subject3, date);
        page.setTotal(total);
        List<Student> ss = studentService.listStudentByNextTimeExam(subject2, subject3, date,page);
        List<Integer> time  = new ArrayList<>();
        List<ExamInfo> es = new ArrayList<>();
        for(Student s : ss){
            time.add(coachService.totalTime(s.getId(),cid));
            ExamInfo e  = examInfoService.getExamInfoByNextTime(s.getId(),date);
            if(e != null){
                e.setDate_();
            }
            es.add(e);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ss", ss);
        jsonObject.put("page", page);
        jsonObject.put("time",time);
        jsonObject.put("es", es);
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }


    @ResponseBody
    @RequestMapping("admin_coach_listStudentByLastTime")
    public String listStudentByLastTime(Page page, HttpSession session){

        User user = (User) session.getAttribute("coach");
        int cid = user.getCoach().getId();
        String type = user.getCoach().getType();
        int typeNum;
        Date date = new Date();
        int subject2=0,subject3=0;
        if(Common.SUBJECT2.equals(type)){
            subject2 = cid;
            typeNum = 2;
        }
        else {
            subject3 = cid;
            typeNum = 3;
        }
        JSONObject jsonObject = new JSONObject();
        ExamInfo examInfo = examInfoService.lastTimeExamInfo(date,typeNum);
        page.setCount(10);
        int total = studentService.totalStudentByLastTimeExamInfo(subject2,subject3,examInfo.getDate());
        page.setTotal(total);
        List<Student> students = studentService.listStudentByLastTimeExamInfo(subject2,subject3,examInfo.getDate(),page);
        for(Student s : students){
            s.getExamInfo().setDate_();
        }
        jsonObject.put("ss", students);
        jsonObject.put("page", page);
        return  jsonObject.toJSONString();
    }



    @ResponseBody
    @RequestMapping("admin_coach_resetStudentExamStatus")
    public String resetStudentStatus(int eid, int sid, int status, HttpSession session){
        //status -1 未通过考试 0未设定 1通过考试
        Student student = studentService.getStudentById(sid);
        Transform transform = new Transform();
        JSONObject jsonObject = new JSONObject();
        int type = transform.change(student.getSchedule());
        if(status == 0){
            examInfoService.updateStudentExamStatus(eid, 1);
            student.setSchedule(transform.change(type + 1 ));
            studentService.update(student);
            // 用户数据变更 删除session
            session.removeAttribute("student");
            // 通过考试
            jsonObject.put("flag", 1);
        }
        else if(status == 1){
            ExamInfo examInfo = examInfoService.getRecentlyExam(student.getId());
            if(eid != examInfo.getId()){
                //已通过考试无法更改
                jsonObject.put("flag", -11);
            }
            else{
                examInfoService.updateStudentExamStatus(eid, -1);
                student.setSchedule(transform.change(type - 1 ));
                studentService.update(student);
                // 未通过考试
                jsonObject.put("flag", -1);
                // 用户数据变更 删除session
                session.removeAttribute("student");
            }
        }
        else if(status == -1){
            ExamInfo examInfo = examInfoService.getRecentlyExam(student.getId());
            if(eid != examInfo.getId()){
                //未通过考试无法更改
                jsonObject.put("flag", -22);
            }
            else{
                examInfoService.updateStudentExamStatus(eid, 1);
                student.setSchedule(transform.change(type + 1));
                studentService.update(student);
                // 通过考试
                jsonObject.put("flag", 1);
                // 用户数据变更 删除session
                session.removeAttribute("student");
            }

        }

        return jsonObject.toJSONString();
    }


    @ResponseBody
    @RequestMapping("foreStudentSelectCoach")
    public String selectCoach(int cid, String coachType, HttpSession session){
        User user = (User) session.getAttribute("student");

        JSONObject jsonObject = new JSONObject();
        if(user == null){
            //-1 用户未登录
            jsonObject.put("flag", "用户未登录");
        } else {

            int coachTypeNum = new Transform().change(coachType);
            Student student = user.getStudent();
            int schedule = new Transform().change(student.getSchedule());

            if(schedule != coachTypeNum){
                jsonObject.put("flag", "教练类型不匹配");
            }
            else{
                if(student.getSubject2() == 0){
                    student.setSubject2(cid);
                    studentService.update(student);
                    jsonObject.put("flag", "success");
                }
                else{
                    jsonObject.put("flag", "已有教练");
                }
            }
        }
        return jsonObject.toJSONString();

    }










}
